package w3_c2_queue;

/**
 * 不浪费空间的版本。
 */
public class LoopQueue3<E> implements Queue<E> {
    E[] data;
    int front, tail, size;

    public LoopQueue3(int capacity) {
        data = (E[]) new Object[capacity];
        front = tail = size = 0;
    }

    public LoopQueue3() {
        this(10);
    }

    public int getSize() {
        return size;
    }

    public int getCapacity() {
        return data.length;
    }

    private void resize(int capacity) {
        E[] newData = (E[]) new Object[capacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        front = 0;
        tail = getSize();
    }

    @Override
    public boolean isEmpty() {
        return getSize() == 0;
    }

    @Override
    public void enqueue(E e) {
        if (size == data.length)
            resize(2 * size);
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty())
            throw new IllegalArgumentException("Cannot dequeue from empty queue.");
        E res = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size--;
        if (getSize() < getCapacity() / 4 && getCapacity() / 2 != 0)
            resize(getCapacity() / 2);
        return res;
    }

    @Override
    public E getFront() {
        return data[front];
    }
    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append(String.format("LooqQueue, size = %d, capacity = %d\n", getSize(), getCapacity()));
        res.append("front [");
        for (int i = 0; i < getSize(); i++){
            res.append(data[(i+front)% data.length]);
            if(i !=  getSize() -1)
                res.append(", ");
        }
        res.append("] tail\n");
        return res.toString();
    }
    public static void main(String[] args) {
        LoopQueue3<Integer> queue3 = new LoopQueue3<>();
        int n = 20;
        for (int i = 0; i < n; i++) {
            queue3.enqueue(i);
            System.out.println(queue3);
        }

        for(int i = 0;i < 20;i++) {
            queue3.dequeue();
            System.out.println(queue3);
        }
    }
}
